package com.enation.app.javashop.core.promotion.groupbuy.service.impl;

import com.enation.app.javashop.core.base.rabbitmq.TimeExecute;
import com.enation.app.javashop.core.promotion.PromotionErrorCode;
import com.enation.app.javashop.core.promotion.groupbuy.model.dos.GroupbuyActiveDO;
import com.enation.app.javashop.core.promotion.groupbuy.model.dos.GroupbuyGoodsDO;
import com.enation.app.javashop.core.promotion.groupbuy.model.enums.GroupBuyGoodsStatusEnum;
import com.enation.app.javashop.core.promotion.groupbuy.model.vo.GroupbuyActiveVO;
import com.enation.app.javashop.core.promotion.groupbuy.service.GroupbuyActiveManager;
import com.enation.app.javashop.core.promotion.groupbuy.service.GroupbuyGoodsManager;
import com.enation.app.javashop.core.promotion.tool.model.dto.PromotionDetailDTO;
import com.enation.app.javashop.core.promotion.tool.model.dto.PromotionGoodsDTO;
import com.enation.app.javashop.core.promotion.tool.model.dto.PromotionPriceDTO;
import com.enation.app.javashop.core.promotion.tool.model.enums.PromotionTypeEnum;
import com.enation.app.javashop.core.promotion.tool.service.PromotionGoodsManager;
import com.enation.app.javashop.core.promotion.tool.service.impl.AbstractPromotionRuleManagerImpl;
import com.enation.app.javashop.core.promotion.tool.support.PromotionCacheKeys;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.trigger.Interface.TimeTrigger;
import com.enation.app.javashop.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 团购活动表业务类
 *
 * @author Snow
 * @version v7.0.0
 * @since v7.0.0
 * 2018-03-21 11:52:14
 */
@Service
public class GroupbuyActiveManagerImpl extends AbstractPromotionRuleManagerImpl implements GroupbuyActiveManager {

    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private GroupbuyGoodsManager groupbuyGoodsManager;

    @Autowired
    private PromotionGoodsManager promotionGoodsManager;

    @Autowired
    private TimeTrigger timeTrigger;

    @Autowired
    private Cache cache;

    @Override
    public Page list(int page, int pageSize) {
        String sql = "select * from es_groupbuy_active order by start_time desc";
        Page webPage = this.daoSupport.queryForPage(sql, page, pageSize, GroupbuyActiveVO.class);
        return webPage;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class})
    public GroupbuyActiveDO add(GroupbuyActiveDO groupbuyActive) {
        this.verifyTime(groupbuyActive.getStartTime(), groupbuyActive.getEndTime(), PromotionTypeEnum.GROUPBUY, null);
        this.verifyName(groupbuyActive.getActName(), false, 0);
        this.daoSupport.insert(groupbuyActive);
        int id = this.daoSupport.getLastId("es_groupbuy_active");
        groupbuyActive.setActId(id);
        return groupbuyActive;
    }

    @Override
    public GroupbuyActiveDO edit(GroupbuyActiveDO groupbuyActive, Integer id) {
        this.verifyTime(groupbuyActive.getStartTime(), groupbuyActive.getEndTime(), PromotionTypeEnum.GROUPBUY, id);

        this.verifyName(groupbuyActive.getActName(), true, id);
        this.verifyAuth(id);
        this.daoSupport.update(groupbuyActive, id);
        return groupbuyActive;
    }

    @Override
    public void delete(Integer id) {
        this.verifyAuth(id);
        this.daoSupport.delete(GroupbuyActiveDO.class, id);
        //删除参加的团购商品
        String sql = "delete from es_groupbuy_goods where act_id = ? ";
        this.daoSupport.execute(sql, id);
    }

    @Override
    public GroupbuyActiveDO getModel(Integer id) {
        return this.daoSupport.queryForObject(GroupbuyActiveDO.class, id);
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class, Exception.class})
    public void reviewGoods(Integer actId, Integer gbId, Integer status) {

        //修改状态
        this.groupbuyGoodsManager.updateStatus(gbId, status);

        //如果通过审核
        if (status.intValue() == GroupBuyGoodsStatusEnum.APPROVED.status()) {

            //修改已参与团购活动的商品数量
            this.daoSupport.execute("update es_groupbuy_active set goods_num=goods_num+1 where act_id=?", actId);

            //活动信息DO
            GroupbuyActiveDO activeDO = this.getModel(actId);

            //读取团购商品
            GroupbuyGoodsDO goodsDO = this.groupbuyGoodsManager.getModel(gbId);

            //商品集合
            List<PromotionGoodsDTO> goodsDTOList = new ArrayList<>();
            PromotionGoodsDTO goodsDTO = new PromotionGoodsDTO();
            goodsDTO.setGoodsName(goodsDO.getGoodsName());
            goodsDTO.setThumbnail(goodsDO.getThumbnail());
            goodsDTO.setGoodsId(goodsDO.getGoodsId());
            goodsDTO.setPrice(goodsDO.getPrice());
            goodsDTO.setQuantity(goodsDO.getGoodsNum());
            goodsDTO.setSellerId(goodsDO.getSellerId());
            goodsDTOList.add(goodsDTO);

            //活动信息DTO
            PromotionDetailDTO detailDTO = new PromotionDetailDTO();
            detailDTO.setActivityId(actId);
            detailDTO.setStartTime(activeDO.getStartTime());
            detailDTO.setEndTime(activeDO.getEndTime());
            detailDTO.setPromotionType(PromotionTypeEnum.GROUPBUY.name());
            detailDTO.setTitle(activeDO.getActName());
            //入库到活动商品对照表
            this.promotionGoodsManager.add(goodsDTOList, detailDTO);
            this.cache.put(PromotionCacheKeys.getGroupbuyKey(actId), goodsDO);
            //将此商品加入延迟加载队列，到指定的时间将索引价格变成最新的优惠价格
            PromotionPriceDTO promotionPriceDTO = new PromotionPriceDTO();
            promotionPriceDTO.setGoodsId(goodsDO.getGoodsId());
            promotionPriceDTO.setPrice(goodsDO.getPrice());
            timeTrigger.add(TimeExecute.PROMOTION_EXECUTER, promotionPriceDTO, activeDO.getStartTime(), null);
            //此活动结束后将索引的优惠价格重置为0
            promotionPriceDTO.setPrice(0.0);
            timeTrigger.add(TimeExecute.PROMOTION_EXECUTER, promotionPriceDTO, activeDO.getEndTime(), null);

        }
    }


    @Override
    public List<GroupbuyActiveDO> getActiveList() {

        long nowTime = DateUtil.getDateline();
        String sql = "select * from es_groupbuy_active where join_end_time>=? order by add_time desc";
        return this.daoSupport.queryForList(sql, GroupbuyActiveDO.class, nowTime);
    }


    @Override
    public void verifyAuth(Integer id) {
        GroupbuyActiveDO activeDO = this.getModel(id);
        long nowTime = DateUtil.getDateline();

        //如果活动起始时间小于现在时间，活动已经开始了。
        if (activeDO.getStartTime().longValue() < nowTime && activeDO.getEndTime().longValue() > nowTime) {
            throw new ServiceException(PromotionErrorCode.E400.code(), "活动已经开始，不能进行编辑删除操作");
        }
    }


}
